<template>
  <div id="PictureDetailPage" class="page-container">
    <!-- 顶部装饰性背景 -->
    <div class="background-decoration"></div>

    <a-card class="main-card" :bordered="false">
      <!-- 顶部面包屑导航 -->
      <div class="breadcrumb-nav">
        <a-breadcrumb>
          <a-breadcrumb-item>
            <router-link to="/">首页</router-link>
          </a-breadcrumb-item>
          <a-breadcrumb-item>
            <router-link to="/books">图书列表</router-link>
          </a-breadcrumb-item>
          <a-breadcrumb-item>{{ book.book_name || '图书详情' }}</a-breadcrumb-item>
        </a-breadcrumb>
      </div>

      <a-row :gutter="[32, 32]">
        <!-- 左侧：图书预览与交互 -->
        <a-col :xs="24" :md="10" :lg="8">
          <div class="preview-section">
            <!-- 图书封面区域 -->
            <div class="cover-container">
              <div class="cover-frame">
                <a-image
                  :src="book.book_url || 'https://via.placeholder.com/300x400?text=图书封面'"
                  :preview="true"
                  class="book-image"
                />
                <div class="cover-shine"></div>
                <!-- 状态标签 -->
                <div
                  class="status-flag"
                  :class="book.book_status === '0' ? 'available' : 'unavailable'"
                >
                  {{ book.book_status === '0' ? '可借阅' : '已借出' }}
                </div>
              </div>

              <!-- 图书标题和作者 -->
              <div class="book-meta">
                <h1 class="book-title">{{ book.book_name || '未命名图书' }}</h1>
                <div class="book-author">{{ book.book_author || '未知作者' }}</div>
                <div class="book-category">
                  <a-tag color="geekblue">{{ book.book_category || '默认分类' }}</a-tag>
                </div>
              </div>
            </div>

            <!-- 互动按钮区域 -->
            <div class="interaction-section">
              <div class="action-buttons">
                <a-button
                  :type="isLiked ? 'primary' : 'default'"
                  @click="handleLike"
                  class="action-btn like-btn"
                  size="large"
                >
                  <template #icon><LikeOutlined /></template>
                  <span class="btn-text">点赞</span>
                  <span class="btn-count">{{ likeCount }}</span>
                </a-button>

                <a-button
                  :type="isCollected ? 'primary' : 'default'"
                  @click="handleCollect"
                  class="action-btn collect-btn"
                  size="large"
                >
                  <template #icon><StarOutlined /></template>
                  <span class="btn-text">收藏</span>
                  <span class="btn-count">{{ collectCount }}</span>
                </a-button>

                <a-button
                  type="default"
                  class="action-btn share-btn"
                  size="large"
                  @click="handleShare"
                >
                  <template #icon><ShareAltOutlined /></template>
                  <span class="btn-text">分享</span>
                </a-button>
              </div>

              <!-- 评分区域 -->
              <div class="rating-section">
                <div class="rating-stars">
                  <a-rate :value="4.5" allow-half disabled />
                  <span class="rating-text">4.5</span>
                </div>
                <div class="rating-count">(128人评价)</div>
              </div>
            </div>
          </div>
        </a-col>

        <!-- 中间：图书信息 -->
        <a-col :xs="24" :md="14" :lg="10">
          <div class="info-section">
            <div class="section-header">
              <div class="section-icon">📚</div>
              <h2 class="section-title">图书信息</h2>
            </div>

            <div class="info-grid">
              <div class="info-item">
                <div class="info-label">ISBN编号</div>
                <div class="info-value code-font">{{ book.book_isbn || '未提供' }}</div>
              </div>

              <div class="info-item">
                <div class="info-label">出版社</div>
                <div class="info-value">{{ book.book_press || '未提供' }}</div>
              </div>

              <div class="info-item">
                <div class="info-label">出版时间</div>
                <div class="info-value">{{ formatDate(book.book_uploadtime) || '未提供' }}</div>
              </div>

              <div class="info-item">
                <div class="info-label">页数</div>
                <div class="info-value">{{ book.book_pagination || '未提供' }}页</div>
              </div>

              <div class="info-item">
                <div class="info-label">价格</div>
                <div class="info-value price-tag">￥{{ book.book_price || '未提供' }}</div>
              </div>

              <div class="info-item">
                <div class="info-label">语言</div>
                <div class="info-value">简体中文</div>
              </div>

              <div class="info-item full-width">
                <div class="info-label">图书简介</div>
                <div class="info-value book-description">
                  {{ book.book_description || '暂无图书简介。' }}
                </div>
              </div>
            </div>

            <!-- 借阅统计 -->
            <div class="borrow-stats">
              <div class="stat-item">
                <div class="stat-number">128</div>
                <div class="stat-label">累计借阅</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">42</div>
                <div class="stat-label">当前借出</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">86%</div>
                <div class="stat-label">归还率</div>
              </div>
            </div>
          </div>
        </a-col>

        <!-- 右侧：借阅操作与评论 -->
        <a-col :xs="24" :lg="6">
          <div class="action-section">
            <!-- 借阅操作卡片 -->
            <div class="borrow-card">
              <div class="card-header">
                <div class="card-icon">⏱️</div>
                <h3 class="card-title">立即借阅</h3>
              </div>

              <div class="card-content">
                <a-alert
                  v-if="book.book_status !== '0'"
                  message="当前图书不可借阅"
                  type="warning"
                  show-icon
                  class="availability-alert"
                />

                <a-form
                  :model="formState"
                  name="basic"
                  autocomplete="off"
                  @finish="handleSubmit"
                  layout="vertical"
                  class="borrow-form"
                >
                  <a-form-item
                    label="预计归还时间"
                    name="recordRemandtime"
                    :rules="[{ required: true, message: '请选择归还时间' }]"
                  >
                    <a-date-picker
                      v-model:value="formState.recordRemandtime"
                      show-time
                      format="YYYY-MM-DD HH:mm:ss"
                      placeholder="选择归还时间（最长7天）"
                      style="width: 100%"
                      :disabled-date="disabledDate"
                      class="date-picker"
                    />
                  </a-form-item>

                  <a-form-item>
                    <a-button
                      type="primary"
                      html-type="submit"
                      size="large"
                      block
                      :disabled="book.book_status !== '0'"
                      class="borrow-btn"
                    >
                      <BookOutlined />
                      {{ book.book_status === '0' ? '立即借阅' : '不可借阅' }}
                    </a-button>
                  </a-form-item>
                </a-form>

                <div class="borrow-tips">
                  <div class="tip-item">
                    <InfoCircleOutlined class="tip-icon" />
                    <span>单次借阅最长7天</span>
                  </div>
                  <div class="tip-item">
                    <SafetyOutlined class="tip-icon" />
                    <span>请按时归还图书</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 快速操作 -->
            <div class="quick-actions">
              <a-button type="default" block class="quick-btn" @click="handlePreview">
                <EyeOutlined />
                在线预览
              </a-button>
              <a-button type="default" block class="quick-btn" @click="handleRecommend">
                <BulbOutlined />
                相似推荐
              </a-button>
            </div>
          </div>
        </a-col>
      </a-row>

      <!-- 评论区域 -->
      <div class="comment-section">
        <div class="section-header">
          <div class="section-icon">💬</div>
          <h2 class="section-title">读者评论</h2>
        </div>

        <div class="comment-container">
          <CommentListPage />
        </div>
      </div>
    </a-card>
  </div>
  <a-back-top type="primary" />
</template>

<script setup lang="ts">
import { getBookVoByIdUsingGet } from '@/api/bookController'
import { addRecordUsingPost } from '@/api/recordController'
import CommentListPage from '@/pages/comment/CommentListPage.vue'
import router from '@/router'
import { useLoginUserStore } from '@/stores/user'
import {
  BookOutlined,
  BulbOutlined,
  EyeOutlined,
  InfoCircleOutlined,
  LikeOutlined,
  SafetyOutlined,
  ShareAltOutlined,
  StarOutlined,
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'

// 初始化依赖
const loginUserStore = useLoginUserStore()
const route = useRoute()
const book = ref<API.BookVO>({})
const bookId = route.params.id as string
const bookRecord = ref<API.RecordAddRequest>({})
// 点赞和收藏状态
const isLiked = ref(false)
const isCollected = ref(false)
const likeCount = ref(42)
const collectCount = ref(18)

// 表单状态
interface FormState {
  recordRemandtime: string
}
const formState = reactive<FormState>({
  recordRemandtime: '',
})

// 获取图书详情
const getPictureDetail = async () => {
  try {
    const res = await getBookVoByIdUsingGet({ book_id: bookId })
    if (res.data.code === 0 && res.data.data) {
      book.value = res.data.data
    } else {
      message.error(`获取图书详情失败：${res.data.message || '未知错误'}`)
    }
  } catch (e: any) {
    message.error(`获取图书详情异常：${e.message || '网络错误'}`)
  }
}

// 日期格式化
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  return dayjs(dateString).format('YYYY年MM月DD日')
}

// 点赞和收藏处理
const handleLike = () => {
  isLiked.value = !isLiked.value
  likeCount.value += isLiked.value ? 1 : -1
  message.success(isLiked.value ? '点赞成功' : '取消点赞')
}

const handleCollect = () => {
  isCollected.value = !isCollected.value
  collectCount.value += isCollected.value ? 1 : -1
  message.success(isCollected.value ? '收藏成功' : '取消收藏')
}

// 分享处理
const handleShare = () => {
  message.info('分享功能开发中')
}

// 预览处理
const handlePreview = () => {
  message.info('预览功能开发中')
}

// 推荐处理
const handleRecommend = () => {
  message.info('推荐功能开发中')
}

// 禁用日期（不能选择今天之前）
const disabledDate = (current: dayjs.Dayjs) => {
  return current && current < dayjs().startOf('day')
}

const getCurrentFormattedTime = (): string => {
  return dayjs().format('YYYY-MM-DD HH:mm:ss')
}

const handleSubmit = async () => {
  const loginUser = loginUserStore.loginUser

  if (!loginUser.id) {
    message.warning('请先登录再借阅图书！')
    router.push({
      path: '/user/login',
      query: { redirect: route.fullPath },
    })
    return
  }

  if (book.value.book_status !== '0') {
    message.warning('当前图书不可借阅，请选择其他图书！')
    return
  }

  const currentTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  const remandTime = dayjs(formState.recordRemandtime)

  if (remandTime.isBefore(currentTime)) {
    message.warning('归还时间不能早于当前时间！')
    return
  }
  if (remandTime.diff(currentTime, 'day') > 7) {
    message.warning('单次借阅最长为7天，请重新选择归还时间！')
    return
  }

  bookRecord.value = {
    book_id: Number(bookId),
    record_bookname: book.value.book_name || '',
    record_bookisbn: book.value.book_isbn || '',
    record_borrower: Number(loginUser.id),
    record_borrowtime: getCurrentFormattedTime(),
    record_remandtime: dayjs(formState.recordRemandtime).format('YYYY-MM-DD HH:mm:ss'),
  }

  try {
    const res = await addRecordUsingPost(bookRecord.value)
    if (res.data.code === 0) {
      message.success('借阅成功！即将跳转到我的借阅列表')
      setTimeout(() => router.push('/my/recordBook'), 1500)
    } else {
      message.error(`借阅失败：${res.data.message || '未知错误'}`)
    }
  } catch (e: any) {
    message.error(`借阅异常：${e.message || '网络错误'}`)
  }
}

onMounted(() => {
  console.log('当前图书ID：', bookId)
  getPictureDetail()
})
</script>

<style lang="scss" scoped>
.page-container {
  background: linear-gradient(135deg, #f8fafc 0%, #eef2f6 100%);
  min-height: 100vh;
  position: relative;
  max-width: 100%;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 240px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  opacity: 0.03;
  z-index: 0;
}

.main-card {
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.08);
  border-radius: 24px;
  border: none;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  position: relative;
  z-index: 1;
  margin: 0 auto;
  max-width: 1400px;

  :deep(.ant-card-body) {
    padding: 40px;
  }
}

.breadcrumb-nav {
  margin-bottom: 30px;

  :deep(.ant-breadcrumb) {
    font-size: 14px;

    a {
      color: #64748b;
      transition: color 0.3s;

      &:hover {
        color: #3b82f6;
      }
    }

    .ant-breadcrumb-separator {
      color: #94a3b8;
    }

    .ant-breadcrumb-link:last-child {
      color: #1e293b;
      font-weight: 500;
    }
  }
}

// 预览区域
.preview-section {
  .cover-container {
    text-align: center;
    margin-bottom: 30px;

    .cover-frame {
      position: relative;
      display: inline-block;
      margin-bottom: 24px;
      border-radius: 16px;
      overflow: hidden;
      box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
      transition: all 0.4s ease;

      &:hover {
        transform: translateY(-8px);
        box-shadow: 0 25px 50px rgba(0, 0, 0, 0.2);
      }

      .book-image {
        width: 100%;
        max-width: 300px;
        height: auto;
        display: block;
        border-radius: 16px;
      }

      .cover-shine {
        position: absolute;
        top: 0;
        left: -100%;
        width: 50%;
        height: 100%;
        background: linear-gradient(
          to right,
          rgba(255, 255, 255, 0) 0%,
          rgba(255, 255, 255, 0.3) 50%,
          rgba(255, 255, 255, 0) 100%
        );
        transform: skewX(-25deg);
        transition: all 0.6s;
      }

      &:hover .cover-shine {
        left: 150%;
      }

      .status-flag {
        position: absolute;
        top: 16px;
        right: 16px;
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
        color: white;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

        &.available {
          background: linear-gradient(135deg, #10b981, #34d399);
        }

        &.unavailable {
          background: linear-gradient(135deg, #ef4444, #f87171);
        }
      }
    }

    .book-meta {
      .book-title {
        font-size: 24px;
        font-weight: 700;
        color: #1e293b;
        margin: 0 0 8px 0;
        line-height: 1.3;
      }

      .book-author {
        font-size: 16px;
        color: #64748b;
        margin-bottom: 12px;
      }

      .book-category {
        :deep(.ant-tag) {
          border: none;
          padding: 6px 12px;
          border-radius: 20px;
          font-weight: 500;
        }
      }
    }
  }

  .interaction-section {
    .action-buttons {
      display: flex;
      gap: 12px;
      margin-bottom: 20px;

      .action-btn {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        height: 48px;
        border-radius: 12px;
        font-weight: 600;
        transition: all 0.3s ease;
        border: 1px solid #e2e8f0;

        .btn-text {
          flex: 1;
          text-align: center;
        }

        .btn-count {
          background: rgba(0, 0, 0, 0.05);
          padding: 2px 8px;
          border-radius: 12px;
          font-size: 12px;
          min-width: 24px;
        }

        &.like-btn:not(.ant-btn-primary) {
          color: #ef4444;
          border-color: #fecaca;

          &:hover {
            background-color: #fef2f2;
            border-color: #fecaca;
            transform: translateY(-2px);
          }
        }

        &.collect-btn:not(.ant-btn-primary) {
          color: #f59e0b;
          border-color: #fef3c7;

          &:hover {
            background-color: #fffbeb;
            border-color: #fef3c7;
            transform: translateY(-2px);
          }
        }

        &.share-btn {
          color: #64748b;

          &:hover {
            background-color: #f8fafc;
            border-color: #cbd5e1;
            transform: translateY(-2px);
          }
        }
      }
    }

    .rating-section {
      text-align: center;
      padding: 16px;
      background: #f8fafc;
      border-radius: 12px;

      .rating-stars {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        margin-bottom: 4px;

        :deep(.ant-rate) {
          color: #fbbf24;
        }

        .rating-text {
          font-size: 18px;
          font-weight: 700;
          color: #1e293b;
        }
      }

      .rating-count {
        font-size: 14px;
        color: #64748b;
      }
    }
  }
}

// 信息区域
.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f1f5f9;

  .section-icon {
    font-size: 24px;
    margin-right: 12px;
  }

  .section-title {
    font-size: 20px;
    font-weight: 700;
    color: #1e293b;
    margin: 0;
    flex: 1;
  }

  .comment-count {
    font-size: 14px;
    color: #64748b;
  }
}

.info-section {
  .info-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 30px;

    .info-item {
      .info-label {
        font-size: 14px;
        color: #64748b;
        margin-bottom: 6px;
        font-weight: 500;
      }

      .info-value {
        font-size: 16px;
        color: #1e293b;
        font-weight: 500;
      }

      .code-font {
        font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', monospace;
        background: #f1f5f9;
        padding: 4px 8px;
        border-radius: 6px;
        display: inline-block;
      }

      .price-tag {
        color: #ef4444;
        font-size: 18px;
        font-weight: 700;
      }

      &.full-width {
        grid-column: 1 / -1;

        .book-description {
          line-height: 1.6;
          color: #475569;
        }
      }
    }
  }

  .borrow-stats {
    display: flex;
    justify-content: space-around;
    background: #f8fafc;
    border-radius: 16px;
    padding: 20px;

    .stat-item {
      text-align: center;

      .stat-number {
        font-size: 24px;
        font-weight: 700;
        color: #3b82f6;
        margin-bottom: 4px;
      }

      .stat-label {
        font-size: 14px;
        color: #64748b;
      }
    }
  }
}

// 操作区域
.action-section {
  .borrow-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
    border: 1px solid #f1f5f9;
    margin-bottom: 20px;
    overflow: hidden;

    .card-header {
      padding: 20px 20px 0;
      display: flex;
      align-items: center;

      .card-icon {
        font-size: 20px;
        margin-right: 10px;
      }

      .card-title {
        font-size: 18px;
        font-weight: 600;
        color: #1e293b;
        margin: 0;
      }
    }

    .card-content {
      padding: 20px;

      .availability-alert {
        margin-bottom: 20px;
        border-radius: 10px;
      }

      .borrow-form {
        .date-picker {
          width: 100%;
        }

        .borrow-btn {
          height: 50px;
          font-size: 16px;
          font-weight: 600;
          border-radius: 12px;
          background: linear-gradient(135deg, #3b82f6, #1d4ed8);
          border: none;
          margin-top: 10px;
          transition: all 0.3s ease;
          box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);

          &:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(59, 130, 246, 0.4);
          }

          &:disabled {
            background: #d9d9d9;
            color: rgba(0, 0, 0, 0.25);
            border-color: #d9d9d9;
            box-shadow: none;
          }
        }
      }

      .borrow-tips {
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid #f1f5f9;

        .tip-item {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          color: #64748b;
          font-size: 14px;

          .tip-icon {
            margin-right: 8px;
            color: #3b82f6;
          }
        }
      }
    }
  }

  .quick-actions {
    display: flex;
    flex-direction: column;
    gap: 12px;

    .quick-btn {
      height: 44px;
      border-radius: 10px;
      border: 1px solid #e2e8f0;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      transition: all 0.3s;

      &:hover {
        border-color: #cbd5e1;
        background: #f8fafc;
        transform: translateY(-2px);
      }
    }
  }
}

// 评论区域
.comment-section {
  margin-top: 40px;

  .comment-container {
    border-radius: 16px;
    background: #fff;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
    border: 1px solid #f1f5f9;
    overflow: hidden;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .main-card :deep(.ant-card-body) {
    padding: 30px;
  }

  .info-grid {
    grid-template-columns: 1fr !important;
  }
}

@media (max-width: 768px) {
  .page-container {
    padding: 10px;
  }

  .main-card :deep(.ant-card-body) {
    padding: 20px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .borrow-stats {
    flex-direction: column;
    gap: 20px;
  }

  .breadcrumb-nav {
    margin-bottom: 20px;
  }
}

// 动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.preview-section,
.info-section,
.action-section,
.comment-section {
  animation: fadeIn 0.6s ease-out;
}

.action-section {
  animation-delay: 0.2s;
}

.comment-section {
  animation-delay: 0.4s;
}
</style>
